const fs = require("fs");
const path = require("path");
const ora = require("ora");
const glob = require("glob");
//const child_process = require("child_process");
const t = require("../config/dict");
const rm = require("rimraf");
const {
  exeCommand,
  exeCommandSpawn,
  isWindows,
  packageManager,
} = require("../lib/utils");

/**
 * 删除指定目录下所有文件和目录
 * @param dir 指定目录
 */
const delDirectory = (dir, callback) => {
  let files = [];
  if (fs.existsSync(dir)) {
    files = fs.readdirSync(dir);
    files.forEach((file, index) => {
      let curPath = path.join(dir, file);
      var stat = fs.statSync(curPath);
      if (stat.isDirectory()) {
        delDirectory(curPath); //递归删除文件夹
      } else if (stat.isFile()) {
        fs.unlinkSync(curPath); //删除文件
      }
    });
    fs.rmdirSync(dir);
  }
  callback && callback();
};

const removeDir = (targetPath, projectName, context, spinner) => {
  const list = glob.sync(targetPath || "*"); // 遍历当前目录
  if (list.length) {
    let bool =
      list.filter((name) => {
        const fileName = path.resolve(process.cwd(), path.join(".", name));
        const isDir = fs.statSync(fileName).isDirectory(); // 使用同步函数 statSync，不使用异步函数stat
        const bool = name.indexOf(projectName) !== -1 && isDir;
        return bool;
      }).length !== 0;
    if (bool) {
      return new Promise((resolve, reject) => {
        const filePath = path.resolve(
          process.cwd(),
          path.join(".", projectName)
        );
        spinner.text = t(context.lang, "清空缓存") + " ...";
        packageManager()
          .run(["cache", "clean", "--force"])
          /* exeCommandSpawn(
          [isWindows ? "npm.cmd" : "npm", "cache", "clean", "--force"].join(
            " "
          ),
          {
            shell: true,
          }
        ) */
          .catch((err) => {
            spinner.fail();
            reject(err);
          })
          .then(() => {
            spinner.text =
              t(context.lang, "删除目录") + " \\" + projectName + " ...";
            fs.rm(
              filePath,
              {
                recursive: true,
              },
              (err) => {
                if (err) {
                  spinner.fail();
                  reject(err);
                  return;
                }
                spinner.succeed();
                resolve();
              }
            );
          });
      });
    } else {
      return Promise.resolve();
    }
  } else {
    return Promise.resolve();
  }
};

module.exports = (targetPath, projectName, context) => {
  const filePath = path.resolve(process.cwd(), path.join(".", projectName));
  let spinner = ora(t(context.lang, "删除目录") + " \\" + projectName + " ...");
  spinner.start();
  return new Promise((resolve, reject) => {
    rm(filePath, (err) => {
      if (err) {
        removeDir(targetPath, projectName, context, spinner)
          .then(() => {
            resolve();
          })
          .catch((err) => reject(err));
        return;
      }
      spinner.succeed();
      resolve();
    });
  });
};
